import { Icon, Tree } from 'antd';
import React, { useCallback, useEffect } from 'react';
import { isFunction } from 'lodash';
import useProcessCatalogTreeData from '../UseProcessCatalogTreeData';

const { TreeNode } = Tree;

function useProcessCatalogTree(props = {}) {
  const { renderTitle, disableTreeNode = () => false, withLeaves = true } = props;

  const { data, loading, refresh, flattenData } = useProcessCatalogTreeData(withLeaves);

  // 渲染树
  const renderTreeNodes = useCallback(
    (data, keyword, flattenData) => {
      return data.map(node => {
        let key = node.catalogId;
        if (node.processId) {
          key = `${key}_${node.processId}`;
        }

        const nodeRef = node;

        const title = isFunction(renderTitle) ? (
          renderTitle(node, keyword)
        ) : (
          <>
            {node.title}
            {!node.leaf && (
              <span style={{ marginLeft: 3, color: '#67d6ac' }}>({node.childCount})</span>
            )}
          </>
        );
        const disabled = disableTreeNode(node, flattenData);

        if (!node.leaf) {
          return (
            <TreeNode
              icon={({ expanded }) => <Icon type={expanded ? 'folder-open' : 'folder'} />}
              title={title}
              key={key}
              value={node.catalogId}
              isLeaf={false}
              dataRef={nodeRef}
              disabled={disabled}
            >
              {renderTreeNodes(node.children, keyword, flattenData)}
            </TreeNode>
          );
        }
        return (
          <TreeNode
            icon={<Icon type="apartment" />}
            key={key}
            value={node.processCode}
            title={title}
            isLeaf
            dataRef={nodeRef}
            disabled={disabled}
          />
        );
      });
    },
    [disableTreeNode, renderTitle]
  );

  // 渲染树
  const renderTree = useCallback(
    keyword => {
      return renderTreeNodes(data, keyword, flattenData);
    },
    [data, renderTreeNodes, flattenData]
  );

  return { renderTree, loading, refresh, data, flattenData };
}

export default useProcessCatalogTree;
